package leetcodecompetition.S114AC;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Siantar
 * @Date: 2023-09-30-23:16
 * @Description: 1.0
 */
public class T8051 {
    int res = 0;

    public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {
        List<Integer>[] lists = new List[n];
        for (int i = 0; i < n; i++) {
            lists[i] = new ArrayList<>();
        }
        for (int[] edge : edges) {
            int x = edge[0], y = edge[1];
            lists[x].add(y);
            lists[y].add(x);
        }
        dfs(-1, 0, lists, values, k);
        return res;
    }

    public long dfs(int pre, int p, List<Integer>[] lists, int[] values, int k) {
        long r = values[p];
        for (int next : lists[p]) {
            if (next != pre) {
                r += dfs(p, next, lists, values, k);
            }
        }
        if (r % k == 0) res++;
        return r;
    }
}
